$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPWMSOPE : "XPWMSOPE" ,
        T_XPINQBOX : "XPINQBOX" ,
        T_XPAPLYWO : "XPAPLYWO" ,
        T_XPINQCOD : "XPINQCOD",
        T_XPAPLYSO : "XPAPLYSO"
    };
    var domObj = {
			$window : $(window),
			$ppboxInfoGrdDiv : $("#ppboxInfoGrdDiv"),
			$ppboxInfoGrd : $("#ppboxInfoGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W              : $(window)           ,
        destShopSelect : $("#destShopSelect"),
        shipUserInput : $("#shipUserInput"),
        ppBoxIDInput : $("#ppBoxIDInput")  ,
        shipboxInput : $("#shipboxInput")  ,
        woIdSelect         : $("#woIdSelect")    ,
        woPlnQtyTxt        : $("#woPlnQtyTxt")   ,
        woWhinQtyTxt       : $("#woWhinQtyTxt")  ,
        woWhinDiffQtyTxt   : $("#woWhinDiffQtyTxt")  ,
        weighingBoxIDInput : $("#weighingBoxIDInput")  ,
        selectGridIdHide : $("#selectGridIdHide")  ,
        ppBoxWeightInput : $("#ppBoxWeightInput")  ,
        mainGrd   :{
            grdId     : $("#ppboxInfoGrd")   ,
            grdPgText : "#ppboxInfoPg"       ,
            fatherDiv : $("#ppboxInfoGrdDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $('#f1_btn'),
        f2 : $('#f2_btn'),
        f4 : $('#f4_btn'),
        f5 : $('#f5_btn'),
        f8 : $('#f8_btn'),
        queryBox : $('#queryBox_btn')
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.80);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.ppBoxIDInput.val("");
            controlsQuery.shipboxInput.val("");
            controlsQuery.shipUserInput.val("");

            controlsQuery.woPlnQtyTxt.val("");
            controlsQuery.woWhinQtyTxt.val("");
            controlsQuery.woWhinDiffQtyTxt.val("");
            controlsQuery.weighingBoxIDInput.val("");
            controlsQuery.selectGridIdHide.val("");
            controlsQuery.ppBoxWeightInput.val("");
        },
        /**
         * 筛选出用户可以操作的仓位 By CMJ
         */
        setDestShopSel : function(){
        	var inObj,outObj;

        	var iary={
        		data_cate : 'DEST',
        		data_ext  : "'F'",
        		user_id   : VAL.EVT_USER
        	};
        	inObj = {
			   trx_id     : 'XPLSTDAT' ,
	           action_flg : 'F'        ,
	           iary       : iary
        	};
        	outObj = comTrxSubSendPostJson(inObj);
        	if(outObj.rtn_code == VAL.NORMAL){
        		_setSelectDate(outObj.tbl_cnt,outObj.oary,"data_id","data_desc","#destShopSelect",true);
        	}
//            addValueByDataCateFnc("#destShopSelect","DEST","data_id");
        },
        iniWeighInput : function(rowid){
            var rowData = controlsQuery.mainGrd.grdId.getRowData(rowid),
                box_id = rowData["box_id"];

                controlsQuery.weighingBoxIDInput.val(box_id);
                controlsQuery.selectGridIdHide.val(rowid);
        },
        iniWoIdSelect : function(){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                iary : {
                	wo_stats : "'WAIT'"
                }
            };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", "wo_id", "#woIdSelect", true);
            }
        },
        getWoInfoFunc : function(){
            var wo_id,
                inObj,
                outObj;

            wo_id = controlsQuery.woIdSelect.val().trim();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                controlsQuery.woPlnQtyTxt.val("");
                controlsQuery.woWhinQtyTxt.val("");
                controlsQuery.woWhinDiffQtyTxt.val("");
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id,
                    mtrl_cate : "SHMT"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                controlsQuery.woPlnQtyTxt.val(outObj.oary.pln_prd_qty);
                controlsQuery.woWhinQtyTxt.val(outObj.oary.wh_in_prd_qty);
                controlsQuery.woWhinDiffQtyTxt.val(
                    parseInt(outObj.oary.pln_prd_qty,10) -
                        parseInt(outObj.oary.wh_in_prd_qty,10) );
            }

            return true;
        },
        setYieldForBoxInfo : function(){

        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        f1_func : function(){
            var inObj, outObj, wo_id,i;

            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'I'           ,
                bnk_flg     : '0'           ,
                box_stat    : "COMP"
            };

            wo_id = controlsQuery.woIdSelect.val().trim();
            if(wo_id){
                inObj.wo_id = wo_id;
            }

            controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                setGridInfo(outObj.box_info, "#ppboxInfoGrd");
            }
            return true;
        },
        //Clear
        f2_func : function(){
            controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
        },
        //Delete
        f4_func : function(){
            var ids = controlsQuery.mainGrd.grdId.jqGrid("getGridParam","selarrrow");
            for ( var i = 0, j = ids.length; i < j; i++) {
                controlsQuery.mainGrd.grdId.jqGrid('delRowData', ids[0]);
            }
        },
        //Weighting
        f5_func : function(){
            var rowid,
                rowData,
                weight;

            rowid = $.trim(controlsQuery.selectGridIdHide.val());
            if(!rowid){
                showErrorDialog("","请双击需要称重的箱号");
                return false;
            }

            weight = $.trim(controlsQuery.ppBoxWeightInput.val());
            if(!weight){
                showErrorDialog("","请输入箱子重量");
                return false;
            }
            if( parseFloat(weight) >= 0) {
                weight = parseFloat(weight);
            }else{
                showErrorDialog("","箱子重量数值不正确，请输入正确数字！");
                return false;
            }

            rowData = controlsQuery.mainGrd.grdId.getRowData(rowid);
            rowData["box_weight"] = weight;
            controlsQuery.mainGrd.grdId.jqGrid('setRowData', rowid, rowData);
            controlsQuery.selectGridIdHide.val("");
            controlsQuery.ppBoxWeightInput.val("");
            controlsQuery.weighingBoxIDInput.val("");
        },
        //WH in
        f8_func : function(){
            var inObj,
                outObj,
                relate_usr, //送货人
                iary = [],
                ids,
                box_cnt,
                dest_shop,
                rowData,
                i,j;

            relate_usr = $.trim(controlsQuery.shipUserInput.val());
            if(!relate_usr){
                showErrorDialog("","请输入送货人！");
                return false;
            }

//            relate_usr = controlsQuery.relateUserInput.val().trim();
//            if(!relate_usr){
//                showErrorDialog("","请输入收货人！");
//                return false;
//            }

            dest_shop = $.trim(controlsQuery.destShopSelect.val());
            
            if(!dest_shop){
                showErrorDialog("","请选择仓位！");
                return false;
            }
            ids = controlsQuery.mainGrd.grdId.jqGrid("getGridParam","selarrrow");
            box_cnt = ids.length;
            if( box_cnt === 0 ){
                showErrorDialog("","请勾选需要入库的箱号。");
                return false;
            }
            for( i = 0; i < box_cnt; i++ ){
                rowData = controlsQuery.mainGrd.grdId.jqGrid('getRowData', ids[i]);
                iary.push({
                    box_id : rowData['box_id'],
                    dest_shop : dest_shop,//按照界面上选择的仓位进行入库
                    wo_id_fk : rowData['wo_id'],
                    prd_qty : rowData['prd_qty'],
                    box_weight : rowData['box_weight'] || 0
                });
                
            }

            inObj = {
                trx_id      : VAL.T_XPWMSOPE,
                action_flg  : 'I'           ,
                evt_user    : VAL.EVT_USER,
                relate_usr  : relate_usr,
                dest_shop   : dest_shop,
                box_cnt     : ids.length,
                iary        : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
//                showSuccessDialog("入库成功！");
                showMessengerSuccessDialog("入库成功!!",1);
                btnFunc.f1_func();
            }
        },
        //Query box in list
        queryBox_func : function(){
            var box_id;

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(!box_id){
                showErrorDialog("","请输入箱号!");
                return false;
            }

            _findRowInGrid('ppboxInfoGrdDiv', controlsQuery.mainGrd.grdId, 'box_id', box_id);
            return true;
        },
        //shipbox
        queryshipBox_func : function(){
            var box_id;

           var ship_box_id = $.trim(controlsQuery.shipboxInput.val());
            if(!ship_box_id){
                showErrorDialog("","请输入出货箱号!");
                return false;
            }
        	var boxinObj = {
                    trx_id      : VAL.T_XPINQBOX,
                    action_flg  : 'G'           ,
                    box_id      : ship_box_id
               };
       		var boxObj = comTrxSubSendPostJson(boxinObj);
               if(boxObj.rtn_code != VAL.NORMAL){
           	    return false;
               }
            _findRowInGrid('ppboxInfoGrdDiv', controlsQuery.mainGrd.grdId, 'box_id', boxObj.box_id);
            return true;
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f2.click(function(){
            btnFunc.f2_func();
        });
        btnQuery.f4.click(function(){
            btnFunc.f4_func();
        });
        btnQuery.f5.click(function(){
            btnFunc.f5_func();
        });
        btnQuery.f8.click(function(){
            btnFunc.f8_func();
        });
        btnQuery.queryBox.click(function(){
            btnFunc.queryBox_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        // 客户代码、客户订单号、内部订单号、箱号、批次号、总数量、
        // 减薄前型号、减薄后型号、镀膜后型号、切割后型、来料厚度、目标厚度、
        // 制程良率、综合良率、
        // 仓位、重量、状态
        var infoCMNew = [
            {name: 'cus_id',      index: 'cus_id',     label: CUS_ID_TAG      , width: CUS_ID_CLM},
            {name: 'so_id',       index: 'so_id',      label: SO_NO_TAG       , width: WO_ID_CLM},
            {name: 'wo_id',       index: 'wo_id',      label: WO_ID_TAG       , width: WO_ID_CLM},
            {name: 'box_id',      index: 'box_id',     label: CRR_ID_TAG      , width: BOX_ID_CLM},
            {name: 'ship_box_id',   index: 'ship_box_id',   label: "出货箱号"   , width: BOX_ID_CLM},
            {name: 'lot_id',      index: 'lot_id',     label: LOT_ID_TAG      , width: LOT_ID_CLM},
            {name: 'prd_qty',     index: 'prd_qty',    label: TOTAL_QTY_TAG   , width: QTY_CLM },

            {name: 'mtrl_prod_id',   index: 'mtrl_prod_id',   label: FROM_MTRL_ID_TAG   , width: MTRL_PROD_ID_CLM},
            {name: 'mdl_id_fk',      index: 'mdl_id_fk',      label: TO_MTRL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'fm_mdl_id_fk',   index: 'fm_mdl_id_fk',   label: FM_MDL_ID_TAG      , width: MDL_ID_CLM},
            {name: 'cut_mdl_id_fk',  index: 'cut_mdl_id_fk',  label: CUT_MDL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'from_thickness', index: 'from_thickness', label: FROM_THICKNESS_TAG , width: QTY_CLM},
            {name: 'to_thickness',   index: 'to_thickness',   label: TO_THICKNESS_TAG   , width: QTY_CLM},

            {name: 'box_fst_yield',  index: 'box_fst_yield',  label: PROC_YIELD_TAG   , width: QTY_CLM},
            {name: 'box_snd_yield',  index: 'box_snd_yield',  label: WHOLE_YIELD_TAG  , width: QTY_CLM},
            {name: 'dest_shop' ,  index: 'dest_shop' , label: DEST_SHOP_TAG    , width: DEST_SHOP_CLM },
            {name: 'box_weight',  index: 'box_weight', label: WEIGHT_TAG       , width: QTY_CLM },
            {name: 'box_stat'  ,  index: 'box_stat'  , label: STATUS_TAG       , width: PRD_STAT_CLM},
            {name: 'ok_cnt',  index: 'ok_cnt',  label: OK_CNT_TAG       , width: QTY_CLM },
            {name: 'ng_cnt',  index: 'ng_cnt',  label: NG_CNT_TAG       , width: QTY_CLM },
            {name: 'sc_cnt',  index: 'sc_cnt',  label: SC_CNT_TAG       , width: QTY_CLM },
            {name: 'gk_cnt',  index: 'gk_cnt',  label: GRADE_CONTROL_TAG, width: QTY_CLM },
            {name: 'lz_cnt',  index: 'lz_cnt',  label: GRADE_SCRP_TAG   , width: QTY_CLM }
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:360,
            width: 980,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            multiselect : true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            fixed: true,
            colModel: infoCMNew,
            ondblClickRow: function(rowid){
                toolFunc.iniWeighInput(rowid);
            }
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.f1.click();
                return false;
            }else if(event.keyCode == F2_KEY){
                btnQuery.f2.click();
                return false;
            }else if (event.keyCode == F3_KEY) {
                btnQuery.f5.click();
                return false;
            }else if (event.keyCode == F4_KEY) {
                btnQuery.f8.click();
                return false;
            }
//            else if (event.keyCode == F5_KEY) {
////                btnQuery.queryBox.click();
//                return false;
//            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
//        controlsQuery.W.resize(function(){
//            toolFunc.resetJqgrid();
//        });

        //Auto query when press enter after keyin prdID
        controlsQuery.ppBoxIDInput.keydown(function(event){
            'use strict';
            var hasFind,
                box_id;
            if(event.keyCode === 13){

                var i, j,
                    grd,
                    hasFound,
                    curRowData,
                    curRowElement,
                    box_id,
                    rowIds,
                    out_box_id,
                    scrollHeight = 0;

                hasFound = false;

                box_id = $.trim(controlsQuery.ppBoxIDInput.val());
                if(!box_id){
                    showErrorDialog("","请输入箱号ID");
                    return false;
                }
                grd = controlsQuery.mainGrd.grdId;

                rowIds = grd.jqGrid('getDataIDs');
                if(rowIds){
                	$("#ppboxInfoGrd tr").removeClass('bg-found').addClass('ui-widget-content');
                    for(i = 0, j = rowIds.length; i < j; i++) {
                        curRowElement = $("#" + rowIds[i]);
                        curRowData = grd.jqGrid('getRowData', rowIds[i]);
                        if( !hasFound && curRowData['box_id'] == box_id){
                           //grd.trigger("reloadGrid");
                            //curRowElement.removeClass('ui-widget-content').addClass('bg-found');
                            if($("#" + curRowElement[0].children[0].children[0].id).attr("checked")!="checked"){
                            grd.jqGrid('setSelection',rowIds[i]);
                            }
                            hasFound = true;
                            //scroll
                            scrollHeight = (curRowElement[0].rowIndex-1) * curRowElement.height();
                            $($('div.ui-jqgrid-bdiv')[1]).scrollTop(scrollHeight);
               			
                			controlsQuery.ppBoxIDInput.val("");
                            break;
                        }
                    }
                    if(!hasFound){
                        showErrorDialog("", "["+ box_id +"]不在列表中！");
                        return false;
                    }
                }
            }
            return true;
        });
        controlsQuery.shipboxInput.keydown(function(event){
            'use strict';
            var hasFind,
                box_id;
            if(event.keyCode === 13){

                var i, j,
                    grd,
                    hasFound,
                    curRowData,
                    curRowElement,
                    ship_box_id,
                    rowIds,
                    out_box_id,
                    scrollHeight = 0;

                hasFound = false;

                ship_box_id = $.trim(controlsQuery.shipboxInput.val());
                if(!ship_box_id){
                    showErrorDialog("","请输入箱号ID");
                    return false;
                }
                grd = controlsQuery.mainGrd.grdId;

                rowIds = grd.jqGrid('getDataIDs');
                if(rowIds){
                	$("#ppboxInfoGrd tr").removeClass('bg-found').addClass('ui-widget-content');
                    for(i = 0, j = rowIds.length; i < j; i++) {
                        curRowElement = $("#" + rowIds[i]);
                        curRowData = grd.jqGrid('getRowData', rowIds[i]);
                        if( !hasFound && curRowData['ship_box_id'] == ship_box_id){
                           //grd.trigger("reloadGrid");
                            //curRowElement.removeClass('ui-widget-content').addClass('bg-found');
                            if($("#" + curRowElement[0].children[0].children[0].id).attr("checked")!="checked"){
                            grd.jqGrid('setSelection',rowIds[i]);
                            }
                            hasFound = true;
                            //scroll
                            scrollHeight = (curRowElement[0].rowIndex-1) * curRowElement.height();
                            $($('div.ui-jqgrid-bdiv')[1]).scrollTop(scrollHeight);
               			
                			controlsQuery.shipboxInput.val("");
                            break;
                        }
                    }
                    if(!hasFound){
                        showErrorDialog("", "["+ shipboxInput +"]不在列表中！");
                        return false;
                    }
                }
            }
            return true;
        });
        controlsQuery.ppBoxWeightInput.keydown(function(event){
            if(event.keyCode === 13){
                btnFunc.f5_func();
            }
        });

        shortCutKeyBind();

        controlsQuery.woIdSelect.change(function(){
            toolFunc.getWoInfoFunc();
        });
    };

    /**
     * Ini view and data
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
        toolFunc.clearInput();
//        toolFunc.resetJqgrid();

        //Ini data
        toolFunc.setDestShopSel();

        //Wo info
        toolFunc.iniWoIdSelect();
        btnQuery.queryBox.hide();

    };

    initializationFunc();
    function resizeFnc(){                                                                      
    	var offsetBottom, divWidth;                                                              
		      
		divWidth = domObj.$ppboxInfoGrdDiv.width();                                   
		offsetBottom = domObj.$window.height() - domObj.$ppboxInfoGrdDiv.offset().top;
		domObj.$ppboxInfoGrdDiv.height(offsetBottom * 0.95);                          
		domObj.$ppboxInfoGrd.setGridWidth(divWidth * 0.99);                   
		domObj.$ppboxInfoGrd.setGridHeight(offsetBottom * 0.99 - 51);               
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	});  
});